package com.springboot.satoken.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.springboot.satoken.entity.User;
import com.springboot.satoken.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Objects;

@RestController
@Slf4j
@RequestMapping("/user/")
public class UserController {

    @Resource
    private UserService userService;
    // 测试登录，浏览器访问： http://localhost:8081/user/doLogin?username=zhang&password=123456
    @RequestMapping("doLogin")
    public String doLogin(String username, String password) {
        // 此处仅作模拟示例，真实项目需要从数据库中查询数据进行比对
        User user = userService.checkLogin(username,password);
        if(Objects.equals(user, null)) {
            return "登录失败";
        }
        StpUtil.login(user.getId());
        return "登录成功";
    }

    // 查询登录状态，浏览器访问： http://localhost:8081/user/isLogin
    @RequestMapping("isLogin")
    public String isLogin() {
        return "当前会话是否登录：" + StpUtil.isLogin();
    }

    @PutMapping("modUser")
    @SaCheckPermission("user.update")
    public SaResult modUser(){
        log.info("修改用户信息");
        StpUtil.checkPermission("user.update");
        log.info("修改用户信息成功");
        return SaResult.ok("success");
    }
    @DeleteMapping("delUser")
    @SaCheckPermission("user.delete")
    public SaResult deleteUser(){
        log.info("删除用户信息");
        //StpUtil.checkPermission("user.update");
        log.info("删除用户信息成功");
        return SaResult.ok("success");
    }
}